package S13.second;

import java.util.*;
import java.util.Map.Entry;

public class S02 { //通讯录
	private static Map<Person, Set<Person>>map=new HashMap<>();
	
	public static void addFriend(Person p1, Person p2) {
		Set<Person> set = map.computeIfAbsent(p1, key->new HashSet<Person>());
		set.add(p2);
//		Set<Person> set = map.get(p1); //上面两行的功能相当于下面注释的代码
//		if(set==null) {
//			set=new HashSet<Person>();
//			map.put(p1, set);
//		}
//		set.add(p2);
	}
	public static int addFriend(Person p1, Set<Person>persons) {
		Set<Person> set = map.computeIfAbsent(p1, key->new HashSet<Person>());
		int count=set.size();//原来的人数
//		persons.forEach(p->addFriend(p1, p));
		set.addAll(persons); //添加集合
		return set.size()-count;
	}
	
	public static void showFriends(Person p1) { //显示指定人的朋友
		Set<Person> set = map.get(p1);
		if(set==null)return;
		System.out.println(p1+" 的朋友：");
		Iterator<Person> it = set.iterator();
		while(it.hasNext()) {
			Person person = it.next();
			System.out.println("\t"+person);
		}
	}
	public static void showFriends() { //显示所有人的通讯录
		Iterator<Entry<Person, Set<Person>>> it = map.entrySet().iterator();
		while(it.hasNext()) {
			Entry<Person, Set<Person>> entry = it.next();
			showFriends(entry.getKey());
		}
	}
	public static void main(String[] args) {
		Person p1 = new Person("zhangsan","13333333333");
		Person p2 = new Person("yangliu","16666666666");
		addFriend(p1, new Person("lisi", "14444444444"));
		addFriend(p1, new Person("wangwu", "15555555555"));
		showFriends(p1);
		addFriend(p2, new Person("lisi", "14444444444"));
		addFriend(p2, map.get(p1));
		System.out.println("--------------------------");
		showFriends();
	}

}
